/*
 * GestureInterpretation.java
 *
 * Author: Kyle Fernald
 * Created: 3-2-2010
 * EE464K Senior Design - University of Texas
 */

package gestureacquisition;

import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiDevice.Info;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Synthesizer;

public class GestureInterpretation {

    private Synthesizer synth;
    private MidiChannel channel;
    private Receiver receiver;

    private int buttonState = 0;
    private ArrayList<Point> points;
    private Point leftPos;
    private Point rightPos;

    public void updateButtons(int button){
        buttonState = button;
        computeGesture();
    }

    public void updatePositions(ArrayList<Point> locations){
        separateData();
        computeGesture();
    }

    public void separateData(){
        //Sort the points:
        Collections.sort(points, new Comparator<Point>(){
            public int compare(Point p1, Point p2) {
                if(p1.y > p2.y){
                    return 1;
                } else if(p1.y == p2.y){
                    return 0;
                }
                return -1;
            }
        });
    }

    public void computeGesture(){

    }

    public boolean init(){
        return initMIDI();
    }

    private boolean initMIDI(){
        try{
            Info[] infos = MidiSystem.getMidiDeviceInfo();
            int x;
            for(x = 0; x < infos.length; x++){
                //System.out.println(infos[x].getName()+'\t'+infos[x].getVendor()+'\t'+infos[x].getClass());
                if(infos[x].getName().contains("LoopBe") && infos[x].getClass().getName().contains("Out")){
                    break;
                }
            }
            receiver = MidiSystem.getMidiDevice(infos[x]).getReceiver();
            System.out.println("Using MIDI receiver: "+infos[x].getName());
        }
        catch(MidiUnavailableException e){
            GestureAcquisitionView.showErrorDialog("INITIALIZE ERROR","Failed to initialize the MIDI controller.",e);
            return false;
        }
        return true;
    }

    public void close(){
        channel.allSoundOff();
        synth.close();
    }
}
